import urllib
import importlib
import sys
from pdfminer.pdfparser import PDFParser, PDFDocument
from pdfminer.pdfdevice import PDFDevice
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import PDFPageAggregator
from pdfminer.layout import LTTextBoxHorizontal, LAParams
from pdfminer.pdfinterp import PDFTextExtractionNotAllowed

# 移除Python 2的兼容代码（Python 3不需要）
# importlib.reload(sys)  # 此代码在Python 3中已废弃且不需要

def parse(DataIO, save_path):
    parser = PDFParser(DataIO)
    doc = PDFDocument()
    parser.set_document(doc)
    doc.set_parser(parser)
    doc.initialize()

    if not doc.is_extractable:
        raise PDFTextExtractionNotAllowed
    else:
        rsrcmagr = PDFResourceManager()
        laparams = LAParams()
        device = PDFPageAggregator(rsrcmagr, laparams=laparams)
        interpreter = PDFPageInterpreter(rsrcmagr, device)

        for page in doc.get_pages():
            interpreter.process_page(page)
            layout = device.get_result()
            for x in layout:
                try:
                    if isinstance(x, LTTextBoxHorizontal):
                        # 关键修改：添加UTF-8编码声明
                        with open(save_path, 'a', encoding='utf-8') as f:
                            result = x.get_text()
                            print(result)
                            f.write(result + "\n")
                except Exception as e:
                    print(f"Failed: {str(e)}")

if __name__ == '__main__':
    # 解析本地PDF
    with open(r'C:\Users\wilso\Documents\PDF2DOOC\pdf\x3.pdf', 'rb') as pdf_html:
        parse(pdf_html, r'C:\Users\wilso\Documents\PDF2DOOC\txt\x3.txt')


#代码来自知乎-黑马程序员Python